package com.jt.controller;

import com.jt.pojo.User;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;

@Controller
@ResponseBody // 1. 将数据转换为JSON字符串返回 2.如果是String类型 将本身返回
@CrossOrigin // 允许跨域
public class UserController {
    /**
     * URL:http://localhost:8080/hello
     *
     * @return 字符串
     */
    @RequestMapping("/hello") // 访问的请求与其匹配
    public String hello() {
        return "你好，springMVC";
    }

    /**
     * URL:http://localhost:8080/findUserByNA?name=jion&age=25
     *
     * @return 数据正确
     */
    @RequestMapping("/findUserByNA")
    public String findUserByNA(String name, int age) {
        return "数据正确：" + name + ":" + age;
    }

    /**
     * 用对象的方式接受
     * URL:http://localhost:8080/findUserByNA1?name=jion&age=25
     *
     * @return 数据正确
     */
    @RequestMapping("/findUserByNA1")
    public String findUserByNA(User user) {
        return user.toString();
    }

    /**
     * URL:http://localhost:8080/hobby?hobby=敲代码,打游戏,睡觉
     */
    @RequestMapping("/hobby")
    public String hobby(String[] hobby) {
        //String[] split = hobby.split(",");

        return Arrays.toString(hobby);
    }

    /**
     * restFul 语法：
     *      1.参数与参数之间使用/分割
     *      2.需要接受的参数使用{}包裹
     *      3.参数接收时采用@PathVariable取值
     * URL:http://localhost:8080/findUser/tomcat/30/男
     *
     */
    @RequestMapping("findUser/{name}/{age}/{sex}")
    public String findUser(@PathVariable String name,
                           @PathVariable String age,
                           @PathVariable String sex){
        return (name+":"+age+":"+sex);
    }
    /**
     * 当参数多时用对象接收
     * URL:http://localhost:8080/findUser1/tomcat/30/男
     */
    @RequestMapping("findUser1/{name}/{age}/{sex}")
    public String findUser(User user){
        return user.toString();
    }

    /**
     * url:http://localhost:8080/findJSON?name=JSON&age=23
     *
     */
    @RequestMapping("/findJSON")
    @ResponseBody // 可加方法和类上
    public User findJSON(User user){
        user.setName("rose");
        user.setAge(12);
        return user;
    }
}
